package com.meraklisina.latexeditor;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import org.w3c.dom.*;

public class i18n {

	private static String languagePreference;
	private static HashMap<String, String> messageMap = new HashMap<String, String>();

	public static void LoadLanguageFiles() {
		ReadLanguagePreference();
		XmlHandler fileHandler = new XmlHandler("messages.xml");
		NodeList messageListt = fileHandler.GetElementsByTagName("Message");
		for (int i = 0; i < messageListt.getLength(); i++) {
			Node messageNode = messageListt.item(i);
			String key = fileHandler.GetChildNodeValue(messageNode, "key");
			String value = fileHandler.GetChildNodeValue(messageNode,
					languagePreference);

			messageMap.put(key, value);
		}

	}

	public static String GetMessage(String key) {
		return messageMap.get(key);
	}

	public static String GetLanguagePreference() {
		return languagePreference;
	}

	private static String ReadLanguagePreference() {
		try {
			FileReader fileReader = new FileReader("config.txt");
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			String stringFromFile = bufferedReader.readLine();
			boolean languageFound = false;

			while (bufferedReader.ready()) {
				stringFromFile = bufferedReader.readLine();
				if (stringFromFile.contains("Language")) {
					languagePreference = bufferedReader.readLine();
					languageFound = true;
				}
			}
			bufferedReader.close();
			
			if (!languageFound) {
				languagePreference = "English";
			}
		} catch (FileNotFoundException fileNotFoundException) {
			return ("Configuration file \"config.txt\" does not exist!\n");
		} catch (IOException ioexception) {
			ioexception.printStackTrace();
			return ("An error occurred while reading \"config.txt\" ");
		}
		return GetLanguagePreference();
	}
}
